package com.letere.util;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.letere.bean.User;

import java.util.Calendar;

/**
 * @author letere
 * @create 2021-01-28 15:32
 */
public class JwtUtil {
    //密钥
    private static String SECRET = "LETERE";

    /**
     * 生成JWT
     * @param user
     * @return
     */
    public static String create(User user) {
        //设置过期时间
        Calendar date = Calendar.getInstance();
        date.add(Calendar.DATE, 7);
//        date.add(Calendar.SECOND, 7);

        String token = JWT.create().withClaim("userId", user.getId())
                .withClaim("username", user.getUsername())
                .withExpiresAt(date.getTime())
                .sign(Algorithm.HMAC256(SECRET));
        return token;
    }

    /**
     * 生成验证器
     * @return
     */
    private static JWTVerifier verifier(){
        return JWT.require(Algorithm.HMAC256(SECRET)).build();
    }

    /**
     * 验证JWT
     * @param token
     * @return
     */
    public static boolean verify(String token) {
        try {
            verifier().verify(token);
        } catch (JWTVerificationException e) {
            return false;
        }
        return true;
    }
}
